import socket
import os
import sys
import struct

def socket_client_file():
    while True:
        try:
            s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            #s.connect(("服务器的ip",端口号))
            s.connect(("112.125.89.8",46366))
        except socket.error as msg:
            print(msg)
            print(sys.exit(1))
        
        #输入当前目录下的 图片名 xxx.jpg “文件路径 绝对路径”
        filepath = input("input the filepath:")
        #filepath = r'D:\DeskTop\hello.txt'
        #将xxx.jpg  “文件”以128sq的格式打包
        fhead = struct.pack(b'128sq',bytes(os.path.basename(filepath),encoding="utf-8"),os.stat(filepath).st_size)
        s.send(fhead)
        #打开要传输的图片
        fp = open(filepath,'rb')
        while True:
            data = fp.read(1024)
            if not data:
                print('{0} send over...',format(filepath))
                break
            s.send(data) #以二进制格式发送图片数据  “文件数据”
        s.close()

def main():
    socket_client_file()

if __name__ == "__main__" :
    main()